<template>
  <div>
    <a-upload
      v-if="!disabled"
      :multiple="multiple"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      @change="handleChanges"
    >
      <a-button
        v-bind="btnAttrs"
        :loading="spinning"
        :disabled="disabled || spinning"
        type="primary"
        class="mb20"
      >
        <a-icon :type="spinning ? 'loading':'upload'" />
        {{ btnName }}
      </a-button>
      <slot name="tips"></slot>
    </a-upload>
    <a-table
      bordered
      rowKey="fileId"
      :columns="columns"
      :data-source="value"
      :loading="loading"
    >
      <span
        slot="serial"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <span
        slot="action"
        slot-scope="text, record"
      >
        <div class="pub-table-list-action">
          <span v-if="!checkVisibleInDetail">
            <a
              href="javascript:"
              @click="$noticeWarning('抱歉，app端无法导出，请在系统电脑端进行导出')"
            >导出</a>
          </span>
          <template v-else>
            <span
              target="_blank"
              @click="$filePreview(record)"
            >查看</span>
            <span>
              <a
                :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileId"
                target="_parent"
              >导出</a>
            </span>
          </template>
          <span
            v-if="!disabled"
            @click="deleteFile(record)"
          >删除</span>
        </div>
      </span>
    </a-table>
  </div>
</template>
<script>
import { deleteFile, uploadFile } from '@/api'
import Vue from 'vue'
import PreView from '@/components/PreView'
import { checkVisibleInDetail } from '@/utils/util'
import debounce from 'lodash/debounce'

export default {
  props: {
    // 业务编码
    businessCode: {
      type: String,
      required: true
    },
    // 是否禁止上传
    disabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    value: {
      type: [Array, Object],
      default() {
        return []
      }
    },
    // 按钮名称
    btnName: {
      type: String,
      default: () => '上传'
    },
    // 按钮属性
    btnAttrs: {
      type: [Object],
      default() {
        return null
      }
    },
    // 默认多选开启
    multiple: {
      type: Boolean,
      default: () => true
    },

    // 可上传数量
    count: {
      type: [String, Number],
      default() {
        return 100
      }
    }
  },
  data() {
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      token: Vue.getAcloudProvider().getAccessToken(),
      loading: false,
      tableData: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'serial',
          width: 70,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '附件名称',
          dataIndex: 'fileName'
        },
        {
          title: '附件格式',
          dataIndex: 'suffixName',
          width: 200
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 一次最多上传
      num: 10,
      // 文件列表
      files: [],
      //上传中
      spinning: false,
      // 临时文件
      temp: []
    }
  },
  methods: {
    // 上传之前
    beforeUpload() {
      return false
    },
    /**
     * @description: 文件上传防抖
     * @param {function}
     * @return {void}
     */
    fileChange: debounce(function () {
      this.handleUploadFun()
    }, 500),
    /**
     * @description: 接管文件上传
     * @param {object} info 文件对象
     * @return {void}
     */
    handleChanges(info) {
      let pass = true
      const { file } = info
      if (file.size / 1024 / 1024 > 500) {
        // 附件大小校验
        // 限制文件大小为500M
        this.sizeDebounce()
        pass = false
      }
      if (pass) {
        this.files.push(file)
        this.fileChange()
      }
    },
    /**
     * @description: 判断及操作上传文件队列
     * @return {void}
     */
    async handleUploadFun() {
      let pass = true
      if (pass && this.value.length + this.files.length > this.count) {
        pass = false
        this.$message.error(`最多上传${this.count}个文件！`)
        this.files = this.files.slice(0, this.count - this.value.length)
      }
      if (this.multiple) {
        if (pass && this.files.length > this.num) {
          this.$message.error(`一次最多上传${this.num}个文件！`)
          this.files = this.files.slice(0, this.num)
        }
      }
      this.spinning = true
      // this.loading = true
      // 防止上传错误一直loading
      try {
        for (let i = 0; i < this.files.length; i++) {
          await this.uploadFun(this.files[i])
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.$emit('input', [...this.$clone(this.value), ...this.temp])
        this.files = []
        this.temp = []
        this.spinning = false
        // this.loading = false
        // this.$emit('update:uploadArrys', this.uploadLists)
        // this.$emit('fileArrysData', this.uploadLists)
      }
    },
    /**
     * @description: 上传函数拆分
     * @param {FormData} data
     * @return {void}
     */
    uploadFun(file) {
      return new Promise(async (resolve, reject) => {
        const fb = new FormData()
        fb.append('file', file)
        fb.append('businessCode', this.businessCode)
        try {
          let res = await uploadFile(fb)
          if (res.code === 200) {
            this.temp.push(res.data)
          }
          resolve()
        } catch (err) {
          console.log(err)
          reject()
        }
      })
    },
    // async customRequest(date) {
    //   if (this.nums <= 0) {
    //     this.numMesgDebounce()
    //     return
    //   }
    //   this.nums--
    //   let file = date.file
    //   const fb = new FormData()
    //   fb.append('file', file)
    //   fb.append('businessCode', this.businessCode)
    //   this.loading = true
    //   try {
    //     let res = await uploadFile(fb).catch((err) => (this.loading = false))
    //     if (res.code === 200) {
    //       let temp = this.$clone(this.value)
    //       temp.push(res.data)
    //       this.$emit('input', temp)
    //     }
    //   } catch (err) {
    //     console.log(err)
    //   } finally {
    //     this.loading = false
    //   }
    // },
    async deleteFile(record) {
      this.$submitConfirm(async () => {
        let commonId = record.originFileObj && record.originFileObj.commonId ? record.originFileObj.commonId : record.commonId
        this.loading = true
        let res = await deleteFile([commonId])
        if (res.data.code === this.SUCCESS_CODE) {
          let temp = this.$clone(this.value)
          let resIndex = temp.findIndex((v) => v.id === record.id)
          if (resIndex !== -1) {
            temp.splice(resIndex, 1)
            this.$emit('input', temp)
          }
        }
        this.loading = false
      }, '确定删除此文件？')
    }
  }
}
</script>
